<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

/**
 * 发票记录管理 
 */

class InvoiceController extends BaseController {
	/*发票信息列表*/
	public function index(){
		$psize = I('get.psize', $this->m_psize,'intval');
		$status = I('get.status',false,'intval');
		$customer_name = I('get.customer_name','','trim');
		$createTime = I('get.create_time','', 'trim');
		$endTime = I('get.end_time','', 'trim');
		$pay_name = I('get.pay_name','','trim');
		
		if( !$psize )
			$psize = $this->m_psize;
		else if( $psize > 20 )
			$psize = $this->m_psize;

		$MInvoice = D("Invoice");
		$wheres = array();
		$map = array();
		$maps = array();
		$wheres['invoice.is_delete'] = array('neq', 1);
		$wheres['user.is_deleted'] = array('neq', 1);
		$wheres['customer.is_delete'] = array('neq', 1);
		if($customer_name){
			if(strlen($customer_name)>3 && is_numeric($customer_name)){
				$maps['customer.phone'] = array('like','%'.$customer_name.'%');
			}
			$maps['customer.nickname'] = array('like','%'.$customer_name.'%');
			$maps['customer.customer_code'] = array('like','%'.$customer_name.'%');
			$maps['_logic'] = 'or';
			$wheres['_complex'] = $maps;
		}
		if($createTime && $endTime && $createTime<=$endTime){
			$create_time = date('Y-m-d 00:00:00',strtotime($createTime));
			$end_time = date('Y-m-d 23:59:59',strtotime($endTime));
			$wheres['invoice.create_time'] = array('between',array($create_time,$end_time));
		}else if($createTime && $endTime && $createTime>$endTime){
			$create_time = date('Y-m-d 23:59:59',strtotime($createTime));
			$end_time = date('Y-m-d 00:00:00',strtotime($endTime));
			$wheres['invoice.create_time'] = array('between',array($end_time,$create_time));
		}else if(!$endTime && $createTime){//结束时间为空
			$create_time = date('Y-m-d 00:00:00',strtotime($createTime));
			$wheres['invoice.create_time'] = array('egt',$create_time);
		}else if($endTime && !$createTime){
			$end_time = date('Y-m-d 23:59:59',strtotime($endTime));
			$wheres['invoice.create_time'] = array('elt',$end_time);
		}
		if($status){
			switch ($status) {
				case '1':	//邮寄中
					$wheres['invoice.status'] = array('eq',1);
					break;
				case '2':	//已邮寄
					$wheres['invoice.status'] = array('eq',2);
					break;
				case '-1':	//无效
					$wheres['invoice.status'] = array('eq',-1);
					break;
				case '3':	//未处理
					$wheres['invoice.status'] = array('eq',0);
					break;
				default:
					$wheres['invoice.status'] = array('EXP','IS NOT NULL');
					break;
			}
		}
		if($pay_name){
			$map['pay_record.pay_name'] = array('like','%'.$pay_name.'%');
			$customerId = M("pay_record")->field("customer_id")->where($map)->select();
			if($customerId){
				foreach ($customerId as $k => $val) {
					$customerIdArr[] = $val['customer_id'];
				}
				$wheres['customer.customer_id'] = array('in',$customerIdArr);
			}else{
				$wheres['customer.customer_id'] = array('EXP','IS NULL');
			}
		}
		$cnt = $MInvoice->join("customer on customer.customer_id=invoice.customer_id")
						->join("user on user.user_id=invoice.creator")
						->where( $wheres )->count();
		$Page = new \Common\ORG\Page( $cnt, $psize );
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$invoice_list = $MInvoice
						->field("invoice.invoice_id,invoice.title,invoice.money,invoice.tax,invoice.type,invoice.payee,
							invoice.remark as inv_remark,invoice.delivery_id,invoice.creator,invoice.creator_role,
							invoice.creator_sector,invoice.creator_sector,invoice.customer_id,invoice.sales_id,invoice.sales_sector,
							invoice.sales_subcompany,invoice.sales_manager,invoice.create_time,invoice.update_time,invoice.status,
							user.nickname as username,customer.nickname,customer.customer_code,customer.mount,customer.remark")
						->join("customer on customer.customer_id=invoice.customer_id")
						->join("user on user.user_id=invoice.creator")
						->where($wheres)
						->order("invoice.update_time desc")
			            ->limit($Page->firstRow.','.$Page->listRows )
			            ->select();
		for($j=0;$j<=$cnt-1;$j++){
			if($invoice_list[$j]['delivery_id']){
				$map[$j] = array();
				$map[$j]['delivery_id'] = array('eq',$invoice_list[$j]['delivery_id']);
				$deliveryInfo[$j] = M("Delivery")->field("*")->where($map[$j])->find();
				if($deliveryInfo[$j]){
					$invoice_list[$j]['deliveryInfo'] = $deliveryInfo[$j];
					$invoice_list[$j]['deliveryStatus'] = $deliveryInfo[$j]['status'];
					if($invoice_list[$j]['deliveryInfo']['send_time'])
						$invoice_list[$j]['deliveryInfo']['send_time'] = date('Y-m-d',strtotime($invoice_list[$j]['deliveryInfo']['send_time']));
				}
			}else if($invoice_list[$j]['invoice_id']&&!$invoice_list[$j]['delivery_id']){
				$invoice_list[$j]['deliveryStatus'] = 50;
			}
			//添加发票流水对应付款人姓名
			$maps1[$j] = array();
			$maps2[$j] = array();
			$maps1[$j]['invoice_id']  = array('eq',$invoice_list[$j]['invoice_id']);
			$pay_id[$j] = M('invoice_pays')->field('pay_id')->where($maps1[$j])->find();
			$maps2[$j]['pay_id'] = array('eq',$pay_id[$j]['pay_id']);
			$payName[$j] = M('pay_record')->field('pay_name')->where($maps2[$j])->find();
			if($payName[$j]){
				$invoice_list[$j]['invpay_name'] = $payName[$j]['pay_name'];
			}
			if($invoice_list[$j]['create_time']){
				$invoice_list[$j]['create_time'] = date('Y-m-d',strtotime($invoice_list[$j]['create_time']));
			}
			if($invoice_list[$j]['update_time']){
				$invoice_list[$j]['update_time'] = date('Y-m-d',strtotime($invoice_list[$j]['update_time']));
			}
		}
		if( $invoice_list ){
			$status = $MInvoice->getStatus();
			$_status = array();
			foreach( $status as $v ){
				$_status[$v['k']] = $v['v'];
			}
			foreach( $invoice_list as &$vi){
				$vi['status_name'] = isset( $_status[$vi['deliveryStatus']]) ?  $_status[$vi['deliveryStatus']] : $vi['deliveryStatus'];
			}
  			$res['rcode'] = 1;
  			$res['msg'] = "OK";
  			$res['data'] = $invoice_list;
  			$res['pall'] =  $Page->getTotalPages();
  			$res['p'] = $Page->nowPage;
		}else{
	       	$res['rcode'] = 2;
			$res['msg'] = "发票信息列表为空";
		}
		e_json( $res );	        
	}

	/*添加普通发票*/
	public function add(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$MInvoice = D("Invoice");
		$delivetype = I('post.delivetype',false,'intval');
		$add_data = array();
		$add_delivery = array();
		//发票信息
		$add_data['customer_id'] = I('post.customer_id','','trim');
		$add_data['title'] = I('post.title','','trim');
        $add_data['payee'] = I('post.payee',false,'intval');
        $add_data['money'] = I('post.money');
        $add_data['tax'] = I('post.tax');
        $add_data['remark'] = I('post.remark','','trim');
        $add_data['status'] = I('post.status',false,'intval');
        $add_data['type'] = 1;
        $add_data['pic_alt'] = I('post.pic_alt','','trim');
        $add_data['pay_id'] = I('post.pay_id','','trim');
        //邮寄信息
        $add_delivery['recipients'] = I('post.recipients','','trim');
        $add_delivery['address'] = I('post.address','','trim');
        $add_delivery['phone'] = I('post.phone','','trim');
        $add_delivery['send_time'] = I('post.send_time','','trim');
        $add_delivery['remark'] = I('post.remark','','trim');
        $addres = $MInvoice->add_invoice( $add_data,$delivetype,$add_delivery );
        if( $addres['r'] ){
			$res['rcode'] = 1;
			$res['msg'] = 'OK';
			$res['data'] = $addres['d'];
		} else{
			$res['msg'] = $addres['i'];
		}
		e_json( $res );
	}
	
	/*编辑普通发票*/
	public function edit(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$MInvoice = D("Invoice");
		$delivery_id = I('post.delivery_id',false,'intval');
		//发票信息
		$edit_data = array();
		$edit_data['customer_id'] = I('post.customer_id','','trim');
		$edit_data['invoice_id'] = I('post.invoice_id',-1,'intval');
		$edit_data['title'] = I('post.title','','trim');
        $edit_data['payee'] = I('post.payee',false,'intval');
        $edit_data['money'] = I('post.money',0,'intval');
        $edit_data['tax'] = I('post.tax',0,'trim');
        $edit_data['remark'] = I('post.edit_remark','','trim');
        $edit_data['pay_id'] = I('post.pay_id');
        //邮寄信息
        $edit_delivery = array();
        if($delivery_id){
        	$edit_delivery['delivery_id'] = $delivery_id;
        }
        $edit_delivery['recipients'] = I('post.recipients','','trim');
        $edit_delivery['address'] = I('post.address','','trim');
        $edit_delivery['phone'] = I('post.phone','','trim');
        $edit_delivery['send_time'] = I('post.send_time','','trim');
        $edit_delivery['remark'] = I('post.remark','','trim');
		$editres = $MInvoice->update_invoice($edit_data,$delivery_id,$edit_delivery);
		if( $editres['r'] ){
			$res['rcode'] = 1;
			$res['msg'] = 'OK';
			$res['data'] = $editres['d'];
		}else{
			$res['msg'] = $editres['i'];
		}
		e_json( $res );
	}

	/*获取客户付款信息*/
	public function getCustomerInfo(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$search_neirong = I('post.search_neirong');
		$invoice_id = I('post.invoice_id');
		$pay_name = I('post.pay_name');
		$customer_id = I('post.customerid');
		$wheres1 = array();
		$MPayrecord = D("Pay_record");
		$MInvoice = D("Invoice");
		$MInvoicePays = M('invoice_pays');
		//编辑发票信息获取对应流水
		if($invoice_id){
			$maps = array();
			$maps['invoice_id'] = array('eq',$invoice_id);
			$payId = $MInvoicePays->field('pay_id')->where($maps)->find();
			$res['invpay_name'] = M("invoice")->where($maps)->getField("title");
			$payIdArr = $MInvoicePays->field('pay_id')->where($maps)->select();
			for ($n=0; $n < count($payIdArr); $n++) { 
				$wh[$n] = array();
				$wh[$n]['pay_id'] = $payIdArr[$n]['pay_id'];
				$customerids[$n] = M("pay_record")->where($wh[$n])->getField('customer_id');
				$wheres1['pay_record.customer_id'] = array('eq', $customerids[$n]);
			}
		}
		if("phone" == $search_neirong){//按照电话号码筛选
			$wheres1['pay_record.customer_id'] = array('eq', $customer_id);
		}else if("payname" == $search_neirong){//按照付款人筛选
			$wheres1['pay_record.pay_name'] = array('eq', $pay_name);
		}
		$wheres1['pay_record.record_status'] = array('eq', 1);
		$order1 = "pay_record.pay_time desc";
		$payrecordInfo = $MPayrecord
                ->field("c.nickname as customer_name,u.nickname as service_name,co.product_id,c.phone,
                	pay_record.pay_mount,pay_record.pay_time,pay_record.audit_res,
                	pay_record.pay_name,pay_record.pay_id,pay_record.invoice_mount")
				->join("JOIN customer c on c.customer_id=pay_record.customer_id")
				->join("JOIN user u on u.user_id=pay_record.sales_person")
				->join("JOIN contract co on co.contract_id=pay_record.contract_id")
				->where( $wheres1 )
				->order( $order1 )
				->select();
		for($i=0;$i<=count($payrecordInfo)-1;$i++){
			//获取产品名
			$map1[$i] = array();
			$map1[$i]['product_id'] = array('eq',$payrecordInfo[$i]['product_id']);
			$productName[$i] = M('Product')->field('name')->where($map1[$i])->find();
			if($productName[$i]){
				$payrecordInfo[$i]['product_name'] = $productName[$i]['name'];
			}
			//判断是否开过发票
			$map2[$i] = array();
			$map2[$i]['pay_id'] = array('eq',$payrecordInfo[$i]['pay_id']);
			if($invoice_id){
				$map2[$i]['invoice_id'] = array('neq',$invoice_id);
			}
			$invInfo[$i] = M('invoice_pays')->field('invoice_pays_id')->where($map2[$i])->find();
			if($invInfo[$i]['invoice_pays_id']){
				$payrecordInfo[$i]['invoiceExist'] = 1;
			}else{
				$payrecordInfo[$i]['invoiceExist'] = 0;
			}
			//判断是否为该流水的发票
			if($payIdArr){
				for ($j=count($payIdArr)-1; $j >= 0; $j--) {
					if($payrecordInfo[$i]['pay_id'] == $payIdArr[$j]['pay_id']){
						$payrecordInfo[$i]['check'] = 1;
					}
				}
			}
			if($payrecordInfo[$i]['pay_time']){
				$payrecordInfo[$i]['pay_time'] = date('Y-m-d',strtotime($payrecordInfo[$i]['pay_time']));;
			}
		}
		$wheres2 = array();
		$wheres2['invoice.customer_id'] = array('eq',$customer_id);
		$wheres2['invoice.is_delete'] = array('neq',1);
		if($invoice_id){
			$wheres2['invoice.invoice_id'] = array('neq',$invoice_id);
		}
		$order2 = "invoice.create_time desc";
		$invoiceInfo = $MInvoice
			->field("user.nickname,invoice.create_time,invoice.money,
				invoice.status,invoice.type,invoice.title,invoice.delivery_id")
			->join("JOIN user on user.user_id=invoice.sales_id")
			->where($wheres2)
			->order($order2)
			->select();
		for ($i=0; $i < count($invoiceInfo) ; $i++) {
			if($invoiceInfo[$i]['delivery_id']){
				$maps[$i] = array();
				$maps[$i]['delivery_id'] = array('eq',$invoiceInfo[$i]['delivery_id']);
				$deliInfo[$i] = M('Delivery')->field('status')->where($maps[$i])->find();
				$invoiceInfo[$i]['deliStatus'] = $deliInfo[$i]['status'];
			}else{
				$invoiceInfo[$i]['deliStatus'] = 50;
			}
			if($invoiceInfo[$i]['create_time']){
				$invoiceInfo[$i]['create_time'] = date('Y-m-d',strtotime($invoiceInfo[$i]['create_time']));
			}
		}
		if( $payrecordInfo ){
			foreach ($payrecordInfo as $payk => $payv) {
				if($payv['pay_mount'])
					$total_paymount += $payv['pay_mount'];
			}
			$res['total_paymount'] = $total_paymount;
			$res['payrecord_rcode'] = 1;
			$res['payrecordInfo'] = $payrecordInfo;
			$res['customerVerify'] = 1;
			$res['msg'] = 'OK';
			$res['rcode'] = 1;
		}
		if($invoiceInfo){
			foreach ($invoiceInfo as $invk => $invv) {
				if($invv['money'])
					$total_money += $invv['money'];
			}
			$res['total_money'] = $total_money;
			$res['invoice_rcode'] = 1;
			$res['invoiceInfo'] = $invoiceInfo;
			$res['customerVerify'] = 1;
			$res['msg'] = 'OK';
			$res['rcode'] = 1;
		}
		if(!$payrecordInfo && !$invoiceInfo){
			$res['payrecord_rcode'] = 2;
			$res['invoice_rcode'] = 2;
			$res['msg'] = '获取客户付款及发票信息失败';
			$res['customerVerify'] = 2;
		}
		e_json( $res );
	}

	/*发票导出*/
	public function invoiceExport(){
		$res = array('rcode'=>0,'data'=>NULL,'msg'=>'OK');
		$GET = $_GET;
		$wheres1 = array();
		$maps = array();
		if($GET['customer_name']){
			if(strlen($GET['customer_name'])>3 && is_numeric($GET['customer_name'])){
				$maps['c.phone'] = array('like','%'.$GET['customer_name'].'%');
			}
			$maps['c.nickname'] = array('like','%'.$GET['customer_name'].'%');
			$maps['c.customer_code'] = array('like','%'.$GET['customer_name'].'%');
			$maps['_logic'] = 'or';
			$wheres1['_complex'] = $maps;
		}
		$createTime = $GET['create_time'];
		$endTime = $GET['end_time'];
		if($createTime && $endTime && $createTime<=$endTime){
			$create_time = date('Y-m-d 00:00:00',strtotime($createTime));
			$end_time = date('Y-m-d 23:59:59',strtotime($endTime));
			$wheres1['invoice.create_time'] = array('between',array($create_time,$end_time));
		}else if($createTime && $endTime && $createTime>$endTime){
			$create_time = date('Y-m-d 23:59:59',strtotime($createTime));
			$end_time = date('Y-m-d 00:00:00',strtotime($endTime));
			$wheres1['invoice.create_time'] = array('between',array($end_time,$create_time));
		}else if(!$endTime && $createTime){//结束时间为空
			$create_time = date('Y-m-d 00:00:00',strtotime($createTime));
			$wheres1['invoice.create_time'] = array('egt',$create_time);
		}else if($endTime && !$createTime){
			$end_time = date('Y-m-d 23:59:59',strtotime($endTime));
			$wheres1['invoice.create_time'] = array('elt',$end_time);
		}
		$status = $GET['status'];
		switch ($status) {
			case '1':	//邮寄中
				$wheres1['invoice.status'] = array('eq',1);
				break;
			case '2':	//已邮寄
				$wheres1['invoice.status'] = array('eq',2);
				break;
			case '-1':	//无效
				$wheres1['invoice.status'] = array('eq',-1);
				break;
			case '3':	//未处理
				$wheres1['invoice.status'] = array('eq',0);
				break;
			default:
				$wheres1['invoice.status'] = array('EXP','IS NOT NULL');
				break;
		}
		if($GET['pay_name']){
			$map['pay_record.pay_name'] = array('like','%'.$GET['pay_name'].'%');
			$customerId = M("pay_record")->field("customer_id")->where($map)->select();
			if($customerId){
				foreach ($customerId as $k => $val) {
					$customerIdArr[] = $val['customer_id'];
				}
				$wheres1['c.customer_id'] = array('in',$customerIdArr);
			}else{
				$wheres1['c.customer_id'] = array('EXP','IN NOT NULL');
			}
		}
		$wheres1['_string'] = '1=1';
		$wheres1['invoice.is_delete'] = array('eq',0);
		$exportInfo = M('Invoice')
				->field("c.nickname as customer_name,c.phone,u.nickname as sales_name,c.customer_id,invoice.*")
				->join("customer c on c.customer_id=invoice.customer_id")
				->join("user u on u.user_id=invoice.sales_id")
				->where($wheres1)
				->order("invoice.update_time desc")
				->select();
		for($i=0;$i<=count($exportInfo)-1;$i++){
			//查找业务员所属团队
			$wheres4[$i] = array();
			$wheres4[$i]['sector_id'] = array('eq',$exportInfo[$i]['sales_subcompany']);
			$parentCompanyName[$i] = M('Sector')->where($wheres4[$i])->getField("sector_name");
			if($parent_company[$i] == "0"){
				$exportInfo[$i]['parentCompanyName'] = "总公司";
			}else{
				$exportInfo[$i]['parentCompanyName'] = $parentCompanyName[$i];
			}
			//关联发票邮寄信息
			if($exportInfo[$i]['delivery_id']){
				$wheres5[$i] = array();
				$wheres5[$i]['delivery_id'] = array('eq',$exportInfo[$i]['delivery_id']);
				$deliveInfo[$i] = M("Delivery")->field("recipients,phone,address,order_num,send_way,send_time,status")->where($wheres5[$i])->find();
				$exportInfo[$i]['deliveInfo'] = $deliveInfo[$i];
			}
			//业务员经理
			if($exportInfo[$i]['sales_manager']){
				$wheres6[$i] = array();
				$wheres6[$i]['user_id'] = array('eq',$exportInfo[$i]['sales_manager']);
				$mangerName[$i] = M("User")->where($wheres6[$i])->getField("nickname");
				$exportInfo[$i]['mangerName'] = $mangerName[$i];
			}else{
				$exportInfo[$i]['mangerName'] = '';
			}
		}
		import("Common.ORG.Excel");
		$SExcel = new \Common\ORG\Excel();
		$SSheet = new \Common\ORG\Sheet("发票数据");
		$column = array('客户姓名','专/普票','发票抬头','开票金额(元)','开票日期','业务员','经理','团队','收件人','电话',
			'地址','邮寄状态','订单号','快递公司','邮寄时间');
		$SSheet->setColumn( $column );
		$SRefund = D('Refund','Service','Admin');
		$_dataOption = $SRefund->reasons();
		$dataOption = array();
		foreach($_dataOption as &$v ){
			$dataOption['k'.$v['id']] = $v['name'];
		}
		if( $exportInfo ){
			foreach($exportInfo as $vd ){
				$row = array();
				$row[] = $vd['customer_name'];   //客户名
				if($vd['type']==1){			//专/普票
					$row[] = '普票';
				}else if($vd['type']==2){
					$row[] = '专票';
				}else{
					$row[] = '';
				}
				$row[] = $vd['title'];  //发票抬头
				$row[] = $vd['money'];	//开票金额
				$row[] = date('Y-m-d',strtotime($vd['create_time']));	//开票日期
				$row[] = $vd['sales_name'];		//业务员
				$row[] = $vd['mangerName'];  //经理
				$row[] = $vd['parentCompanyName'];	//团队
				$row[] = $vd['deliveInfo']['recipients'];	//收件人
				$row[] = ' '.$vd['deliveInfo']['phone'];	//收件人电话
				$row[] = $vd['deliveInfo']['address'];	//收件地址
				if($vd['deliveInfo']['status']!=NULL){	//邮寄状态
					$deliStatus = "";
					switch ($vd['deliveInfo']['status']) {
						case '10':
							$deliStatus = '待邮寄';
						break;
						case '20': 
							$deliStatus = '确认邮寄';
						break;
						case '30': 
							$deliStatus = '邮寄中';
						break;
						case '40': 
							$deliStatus = '邮寄完成';
						break;
		            }
		            $row[] = $deliStatus;
				}else if($vd['delivery_id']==NULL){
					$deliStatus = '自取';
					$row[] = $deliStatus;
				}
				$row[] = ' '.$vd['deliveInfo']['order_num'];	//订单号
				$row[] = $vd['deliveInfo']['send_way'];		//邮寄公司
				$row[] = date('Y-m-d',strtotime($vd['deliveInfo']['send_time']));//邮寄开始时间
				$SSheet->addRow( $row );
			}
		}
		$exportData = $SExcel->add_sheet( $SSheet)->export_sheet("发票数据导出");
		if( $exportData['rcode'] ){
			$exportData['name'] = basename( $exportData['data']['view_path'] );
			$exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
			echo $exportData['excel'];
			exit();
		}
	}

	/*获取邮寄信息*/
	public function getDeliInfo(){
		$delivery_id = I('get.delivery_id');
		$MDelivery = M('Delivery');
		$wheres = array();
		$wheres['delivery_id'] = $delivery_id;
		$deliveryInfo = $MDelivery->field('*')->where($wheres)->find();
		e_json($deliveryInfo);
	}

	/*绑定邮寄信息*/
	public function bindDelivery(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$invoice_id = I('get.invoice_id',false,'intval');
		$delivery_id = I('get.delivery_id',false,'intval');
		$wheres = array();
		$wheres['invoice_id'] = array('eq',$invoice_id);
		$d = array();
		$d['delivery_id'] = $delivery_id;
		$d['update_time'] = date('Y-m-d H:i:s');
		$bindStatus = M('Invoice')->where( $wheres )->save( $d );
        if( $bindStatus ){
			$res['rcode'] = 1;
			$res['msg'] = '邮寄信息添加成功！';
			$res['data'] = M('Invoice')->where( $wheres )->save( $d );
		}
		else{
			$res['msg'] = '绑定邮寄信息失败！';
		}
		e_json( $res );
	}

    /*获取专票图片--添加页面*/
	public function addImgs(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> '');
		$upload = new \Vendor\Upload\Upload();
    	$upload->maxSize   =     3145728;
    	$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
    	$upload->rootPath  =      './../www/uploads';
    	$upload->savePath  =      '/imgs/';
    	$info = $upload->upload();
    	if($info){
    		$res['data'] = $info;
    		$res['rcode'] = 1;
    	}else{
    		$res['data'] = NULL;
    		$res['msg'] = '图片上传失败，请重新添加！';
    	}
    	e_json($res);
	}

	/*添加专票信息*/
	public function addSpecial(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$MInvoice = D("Invoice");
		$url = urldecode($_POST['d']);
		$imgArr = $_POST['array'];
		$money = $MInvoice->cutStr('&imgPost_money=','&',$url);
		$title = $MInvoice->cutStr('imgPost_title=','&',$url);
		$pic_alt = $MInvoice->cutStr('&pic_alt=','&',$url);
		$status = $MInvoice->cutStr('&status=','&',$url);
		$customer_arr = explode('customer_id=',$url);
		$customer_id = $customer_arr[1];
		//发票信息
		$add_data = array();
		$add_data['customer_id'] = $customer_id;
		$add_data['title'] = $title;
        $add_data['money'] = $money;
        $add_data['tax'] = round($money-$money/1.06);//计算税额
        $add_data['pic_alt'] = $pic_alt;
        $add_data['type'] = 2;	//专票
        $add_data['pay_id'] = $MInvoice->cutStr('&pay_id=','&',$url);
        $add_data['status'] = $MInvoice->cutStr('&status=','&',$url);
        $add_data['remark'] = $pic_alt;
        $delivetype = $MInvoice->cutStr('&delivetype=','&',$url);
        //邮寄信息
        $add_delivery = array();
        $add_delivery['recipients'] = $MInvoice->cutStr('&recipients=','&',$url);
        $add_delivery['address'] = $MInvoice->cutStr('&address=','&',$url);
        $add_delivery['phone'] = $MInvoice->cutStr('&phone=','&',$url);
        $add_delivery['send_time'] = $MInvoice->cutStr('&send_time=','&',$url);
        $add_delivery['remark'] = $MInvoice->cutStr('&remark=','&',$url);
        $addres = $MInvoice->add_invoice($add_data,$delivetype,$add_delivery);
        if( $addres['r'] ){
			//获取发票id后存入invoice_pic表
			$dataImg = array();
			$dataImg['pic_alt'] = $pic_alt;
			$dataImg['invoice_id'] = $addres['invoice_id'];
			$i = 0;
			foreach ($imgArr as $ik => $ival) {
				$i++;
				$dataImg['pic_path'] = '../uploads'.stripcslashes($ival['savepath']).stripcslashes($ival['savename']);
				$dataImg['pic_order'] = $i;
				$addId = M('invoice_pic')->add($dataImg);
				if($addId){
					$res['rcode'] = 1;
					$res['msg'] = 'OK';
				}else{
					$res['rcode'] = 0;
					$res['msg'] = '专票信息添加失败,请重新添加！';
					e_json($res);
				}
	    	}
		} else{
			$res['msg'] = $addres['i'];
		}
		$res['invoice_id'] = $addres['invoice_id'];
        $res['sales_id'] = $addres['sales_id'];
        $res['sales_manager'] = $addres['sales_manager'];
        $res['sales_subcompany'] = $addres['sales_subcompany'];
        $res['customer_id'] = $addres['customer_id'];
        $res['sales_sector'] = $addres['sales_sector'];
		e_json($res);
	}

	/*获取专票图片--编辑页面*/
	public function editImg(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'ok');
		$upload = new \Vendor\Upload\Upload();
    	$upload->maxSize   =     3145728 ;
    	$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
    	$upload->rootPath  =      './../www/uploads';
    	$upload->savePath  =      '/imgs/';
    	$info = $upload->upload();
    	if($info){
    		$res['data'] = $info;
    		$res['rcode'] = 1;
    	}else{
    		$res['msg'] = '图片上传失败，请重新添加！';
    	}
    	e_json($res);
	}

	/*编辑专票信息*/
	public function editSpecial(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'ok');
		$MInvoice = D("Invoice");
		$url = urldecode($_POST['d']);
		$imgArr = $_POST['array'];
		$title = $MInvoice->cutStr('imgPostEdit_title=','&',$url);
		$money = $MInvoice->cutStr('imgPostEdit_money=','&',$url);
		$pic_alt = $MInvoice->cutStr('edit_pic_alt=','&',$url);
		$pay_id = $MInvoice->cutStr('pay_id=','&',$url);
		$invoiceid_arr = explode('invoice_id=',$url);//获取图片对应发票id
		$invoice_id = intval($invoiceid_arr[1]);
		$delivery_id = $MInvoice->cutStr('delivery_id=','&',$url);
		//发票信息
		$edit_data = array();
		$edit_data['invoice_id'] = $invoice_id;
		$edit_data['title'] = $title;
        $edit_data['money'] = $money;
        $edit_data['tax'] = round($money-$money/1.06);//计算税额
        $edit_data['type'] = 2;	//专票
        $edit_data['pay_id'] = $pay_id;
        //邮寄信息
        $edit_delivery = array();
        if($delivery_id){
        	$edit_delivery['delivery_id'] = $delivery_id;
        }
        $edit_delivery['recipients'] = $MInvoice->cutStr('recipients=','&',$url);
        $edit_delivery['address'] = $MInvoice->cutStr('address=','&',$url);
        $edit_delivery['phone'] = $MInvoice->cutStr('phone=','&',$url);
        $edit_delivery['send_time'] = $MInvoice->cutStr('send_time=','&',$url);
        $edit_delivery['remark'] = $MInvoice->cutStr('remark=','&',$url);
        $editres = $MInvoice->update_invoice($edit_data,$delivery_id,$edit_delivery);
        if($editres['r'] == 0){
			$res['msg'] = $editres['i'];
			e_json($res);
		}else{
			$res['data'] = $editres['d'];
		}
        $changePic = $MInvoice->changePicAlt($invoice_id,$pic_alt);
    	if($changePic['r'] == 0){
    		$res['msg'] = $editPicalt['i'];
			e_json($res);
		}
    	//删除原来信息
    	$MInvoicePic = M('invoice_pic');
        $wheres = array();
        $wheres['invoice_id'] = $invoice_id;
        $delePic = $MInvoicePic->where($wheres)->delete();
    	$dataImg = array();
		$dataImg['pic_alt'] = $pic_alt;
		$dataImg['invoice_id'] = $invoice_id;
		$i = 0;
		foreach ($imgArr as $ik => $ival) {
			$i++;
			if($ival['invoice_pic_id']){
				$dataImg['pic_path'] = $ival['pic_path'];
			}else{
				$dataImg['pic_path'] = '../uploads'.stripcslashes($ival['savepath']).stripcslashes($ival['savename']);
			}
			$dataImg['pic_order'] = $i;
			$addId = $MInvoice->addInvoicePic($dataImg);
			if($addId){
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
			}else{
				$res['rcode'] = 0;
				$res['msg'] = '专票信息添加失败,请重新添加！';
				e_json($res);
			}
    	}
        $res['$invoice_id'] = $invoice_id;
        $res['dataImg'] = $dataImg;
		e_json($res);
	}

	//根据发票id获取图片信息
	public function getInvImag(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$invoice_id = I('get.invoice_id');
		$wheres = array();
		$wheres['invoice_id'] = array('eq',$invoice_id);
		$imgInfo = M('invoice_pic')->field('*')->where($wheres)->select();
		if($imgInfo) {
			$res['rcode'] = 1;
			$res['data'] = $imgInfo;
		}
		e_json($res);
	}

	//根据根据payrecord_id获取付款信息、客户基本信息、邮寄信息
	public function getPayInfos(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$pay_id = I('get.pay_id','','trim');
		$MPayrecord = M('Pay_record');
		$wheres1 = array();
		$wheres1['pay_id'] = array('in',$pay_id);
		$wheres1['record_status'] = array('eq',1);
		$payMountSum = $MPayrecord->field('sum(pay_mount) as paymount')->where($wheres1)->find();
		
		$wheres2 = array();
		$wheres2['pay_record.pay_id'] = array('eq',$pay_id);
		$customerInfo = $MPayrecord
						->join('customer c on c.customer_id = pay_record.customer_id')
						->field('c.nickname,c.phone,c.address,pay_record.pay_name')
						->where($wheres2)
						->find();
		$order = "d.send_time desc"; 
		$deliveInfo = $MPayrecord
						->join('delivery d on d.customer_id = pay_record.customer_id')
						->field('d.recipients as nickname,d.phone,d.address,d.send_time')
						->where($wheres2)
						->order($order)
						->select();
		if($payMountSum){
			$res['rcode'] = 1;
			$res['payMountSum'] = $payMountSum;
			$res['customerInfo'] = $customerInfo;
			$res['deliveInfo'] = $deliveInfo;
		}else{
			$res['rcode'] = 0;
			$res['msg'] = '获取客户付款信息失败！';
		}
		e_json($res);
	}

	//根据客户id获取客户名
	public function getCustomerName(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$customer_id = I('post.customer_id',false,'intval');
		$MCustomer = M('Customer');
		$wheres = array();
		$wheres['customer_id'] = array('eq',$customer_id);
		$customerName = $MCustomer->field("nickname")->where($wheres)->find();
		if($customerName['nickname']){
			$res['nickname'] = $customerName['nickname'];
			$res['rcode'] = 1;
		}else{
			$res['msg'] = "客户不存在";
		}
		e_json($res);
	}

	//判断输入付款人是否存在
	public function getCustomerId(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK', 'search_neirong'=>NULL);
		$pay_name = I('post.pay_name');
		// $wheres = array();
		// if( $pay_name ){
		// 	if(strlen($pay_name) > 3 && is_numeric($pay_name)) 
		// 		$wheres['customer.phone'] = array('like','%'.$pay_name.'%');
		// 	else
		// 		$wheres['pay_record.pay_name'] = array('like','%'.$pay_name.'%');
		// }
		// $wheres['pay_record.audit_res'] = array('eq',1);
		// $customerInfo = M('Customer')
		// 				->field("pay_record.pay_name,customer.customer_id,customer.phone,customer.customer_code")
		// 				->join("pay_record on pay_record.customer_id=customer.customer_id")
		// 				->where($wheres)
		// 				->group('pay_record.pay_name')
		// 				->select();
		$wheres = array();
		if( $pay_name ){
			if(strlen($pay_name) > 3 && is_numeric($pay_name)){
				$wheres['phone'] = array('like','%'.$pay_name.'%');
				$wheres['is_delete'] = array('neq', 1);
				$customerInfo = M('Customer')
						->field("nickname as pay_name,customer_id,phone,customer_code")
						->where($wheres)
						->select();
			}else{
				$wheres['pay_record.audit_res'] = array('eq',1);
				$wheres['customer.is_delete'] = array('neq', 1);
				$wheres['pay_record.pay_name'] = array('like','%'.$pay_name.'%');
				$customerInfo = M('Customer')
						->field("pay_record.pay_name,customer.customer_id,customer.phone,customer.customer_code")
						->join("pay_record on pay_record.customer_id=customer.customer_id")
						->where($wheres)
						->group('pay_record.pay_name')
						->select();
			}
		}
		
		for ($i=0; $i < count($customerInfo); $i++) { 
			if(strlen($pay_name) > 3 && is_numeric($pay_name))
				$customerInfo[$i]['search_neirong'] = "phone";
			else 
				$customerInfo[$i]['search_neirong'] = "payname";
		}
		if($customerInfo){
			$res['data'] = $customerInfo;
			$res['rcode'] = 1;
		}else{
			$msg = "客户不存在";
		}
		e_json($res);
	}

	//根据发票id获取对应流水付款人信息
	public function getpay_name(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$invoice_id = I('get.invoice_id',false,'intval');
		$wheres1 = array();
		$wheres2 = array();
		$wheres1['invoice_id'] = array('eq',$invoice_id);
		$pay_Id = M('invoice_pays')->field('pay_id')->where($wheres1)->find();
		$wheres2['pay_id'] = array('eq',$pay_Id['pay_id']);
		$payName = M('pay_record')->field('pay_name')->where($wheres2)->find();
		if($payName){
			$res['data'] = $payName;
		}else{
			$res['msg'] = '数据错误，未找到相关付款人！';
		}
		e_json($res);
	}

}